//
//  FastLoad.m
//  GoFactory
//
//  Created by wtb on 2021/2/2.
//  Copyright © 2021 KQZK. All rights reserved.
//

#import "FastLoad.h"

@interface FastLoad()
@property(nonatomic,strong) NSMutableArray *tasks;
@property(nonatomic,assign) int maxQueueCount;//队列任务数量
@end
@implementation FastLoad

-(instancetype)initWithMaxQueueCount:(int)maxQueueCount{
    if (self = [super init]) {
        _maxQueueCount = (int)maxQueueCount;
        [self addRunloopObserver];
    }
    return self;
}

-(instancetype)init{
    if (self = [super init]) {
        _maxQueueCount = 20;
        [self addRunloopObserver];
    }
    return self;
}

-(NSMutableArray *)tasks{
    if (!_tasks) {
        _tasks = [NSMutableArray array];
    }
    return _tasks;
}

#pragma mark - CFRunloop
-(void)addTasks:(GFRunloopBlock)task{
    [self.tasks addObject:task];
    if (self.tasks.count > self.maxQueueCount) {
        [self.tasks removeObjectAtIndex:0];
    }
}

-(void)addRunloopObserver{
    //获取runloop
    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    
    __weak __typeof(self)GF = self;
    CFRunLoopObserverContext context = {
        0,
        (__bridge void *)GF.tasks,
        &CFRetain,
        &CFRelease,
        NULL
    };

    static CFRunLoopObserverRef runloopObserver;
    runloopObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, 0, &callBackMouldImage, &context);

    CFRunLoopAddObserver(runloop, runloopObserver, kCFRunLoopCommonModes);
    
    CFRelease(runloopObserver);
}


static void callBackMouldImage(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
    NSMutableArray *tasks = (__bridge NSMutableArray*)info;
    if (tasks.count == 0) {
        return;
    }
    GFRunloopBlock task = tasks.firstObject;
    task();
    [tasks removeObjectAtIndex:0];
}
@end
